<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use function AlibabaCloud\Client\arrayMerge;
use app\admin\model\Changyong;
use app\admin\model\DingdanModel;
use app\admin\model\OrderModel;
use app\admin\model\Quxiaoorder;
use app\admin\model\WeixiouModel;
use app\lib\SendSms;
use org\Tree;
use think\Db;
use think\Request;

class Order extends Base
{

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $config = db('config')->where('id',1)->find();
        $exp_time = $config['exp_time'] * 60 + time();
        db('orders')->where(['addtime'=>['lt',$exp_time],'status'=>1])->delete();
    }

    // 商城订单列表
    public function index()
    {
        if(request()->isAjax()){

            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];
            if (!empty($param['searchText']['order_mun'])) {
                $where = ['order_mun'=>$param['searchText']['order_mun']];
            }
            if (!empty($param['searchText']['phone'])) {
               $where['phone'] = $param['searchText']['phone'];
            }
            if (!empty($param['searchText']['status'])) {
                $where =['status'=>$param['searchText']['status']] ;
            }
            if (!empty($param['searchText']['addtime'])) {
                list($start,$end) = explode('~',trim($param['searchText']['addtime']));
                $where['addtime'] = [['gt',strtotime($start)],['lt',strtotime($end)]];
            }
//            var_export($where);die;
//            $where['type'] = 1;
            $order = new OrderModel();
            $selectResult = $order->getOrderByWhere( $where,$offset, $limit);

            foreach($selectResult as $key=>$vo){
                $selectResult[$key]['operate'] = showOperate($this->makeButton($vo['order_mun']));


            }

            $return['total'] = $order->getAllOrder($where);  // 总数据
            $return['rows'] = $selectResult;

            return json($return);
        }
        $this->assign('orderstatus',config('order_status'));
        return $this->fetch();
    }
    //订单详情
    public function orderinfo(){
        $order_mun = input('id');
        $order = db('orders')->where('order_mun',$order_mun)->select();
        $liucheng1 = json_decode(json_encode((new WeixiouModel())->getlist($order_mun)),true);
        $liucheng2 = json_decode(json_encode((new Quxiaoorder())->getlist($order_mun)),true);

        $liucheng = array_merge_recursive($liucheng1,$liucheng2);
        $addtime = array_column($liucheng,'addtime');
        array_multisort($addtime,SORT_DESC,$liucheng);


        $peijian = Db::name('weixiou_j')->where(['orderid'=>$order_mun])->find();
        $this->assign('orderinfo',$order);
        $this->assign('liucheng',$liucheng);
        $this->assign('peijian',$peijian);
        return $this->fetch();
    }
    //发布订单列表
    public function orderlist(){

        $this->assign('orderstatus',config('order_status'));
        return $this->fetch();
    }

    public function orderinfos(){
        $id = input('id');
        $order = db('dingdan')->alias('a')
            ->join('fenlei b','a.fenlei_id = b.id','LEFT')
            ->field('a.*,b.name as goods_name')
            ->where('a.id',$id)
            ->find();
        $order['munber'] = 1;
        $addr=[];
        if ($order){
            $addr = db('addr')->alias('a')
                ->join('area b','a.sheng = b.id','LEFT')
                ->join('area c','a.shi = c.id','LEFT')
                ->join('area d','a.xian = d.id','LEFT')
                ->where('a.addr_id',$order['addr_id'])
                ->field('a.*,b.name as bname,c.name as cname,d.name as dname')
                ->find();
            $addr['order_mun'] = $order['order_mun'];
            $addr['addtime'] = $order['addtime'];
            $addr['servcietime'] = $order['sevrice_time'];

        }

        $this->assign('orderinfo',$order);
        $this->assign('addr',$addr);
        return $this->fetch();

    }
    /**
     * 修改联系方式
     */
    public function editaddr(Request $request){
        try{
            $param = $request->post();
            $param['servcietime'] = strtotime($param['servcietime']);//var_export($param);die;
            $order_mun = $param['order_mun'];
            unset($param['$order_mun']);
            $re = Db::name('orders')->where('order_mun',$order_mun)->update($param);
            if ($re){
                return msg(1,url('index'),'修改成功!');
            }
        }catch (\Exception $e){

                return msg(-1,url('index'),$e->getMessage());

        }

    }

    /**
     * 发送推送消息
     * @param Request $request
     * @return mixed
     */
    public function tuisong(Request $request){
        if ($request -> isAjax()){
            $param = $request -> param();
            $re =  (new  OrderModel())->editOrder($param);

            return json(['code'=>$re['code'],'data'=>$re['data'],'msg'=>$re['msg']]);

        }
        $chang = Changyong::all();
        $this->assign('order_member',$request->param('id'));
        $this->assign('changyong',$chang);
        return $this->fetch();
    }

    /**
     * 添加订单
     */
    public function add(Request $request){
        if ($request->isAjax()){
            return (new OrderModel())->add($request->param());
        }
        return $this->fetch();
    }
    /**
     * 获取分类
     */
    public function ajxgetfenlei(){
        $data = Db::name('fenlei')->where('pid',0)->select();
        return $this->sethtml($data,'name');
    }
    /**
     * 获取分类商品
     */
    public function ajxgetgoods(Request $request){
        $data = Db::name('goods')->where('cat_id',$request->param('fenlei_id'))->select();
        return $this->sethtml($data,'goods_name');
    }
    /**
     * 获取产品属性
     */
    public function ajxgetsuxin(Request $request){
        $data = Db::name('shuxing')->where('goods_id',$request->param('shuxin_id'))->select();
        return $this->sethtml($data,'name');
    }

    /**
     * 获取省
     * @param Request $request
     */
    public function ajxgetprovince(){
        $data = Db::name('area')->where('parent_id',0)->select();
        return $this->sethtml($data,'name');
    }
    /**
     * 获取市
     */
    public function ajxgetcity(Request $request){
        $data = Db::name('area')->where('parent_id',$request->param('province'))->select();
        return $this->sethtml($data,'name');
    }
    /**
     * @return \think\response\Json
     */
    private function sethtml($data,$op){
        $html = '<option value="">请选择</option>';
        foreach ($data as $v){
            $html .= "<option value=".$v['id'].">".$v[$op]."</option>";
        }
        return $html;
    }
    /**
     * 发送短信
     */
    public function sendSms(Request $request){
        if ($request->isAjax()){
            $order = OrderModel::where('order_mun',$request->param('order_mun'))->find();
            OrderModel::where('order_mun',$request->param('order_mun'))->update(['duanxin'=>1]);
            $re = (new  SendSms($order['phone']))->toSendCode();
            if ($re){
                return msg(1,url('index'),'发送成功!');
            }else{
                return msg(-1,[],'发送失败!');
            }
        }
    }

    /**
     * 订单审核
     */

    public function shenhe(Request $request){
        if ($request->isAjax()){
            $weixiou_h = db('weixiou_j')->where(['orderid'=>$request->param('order_mun')])->find();
            qianbao($weixiou_h['total_price'],$request->param('order_mun'));
            OrderModel::where('order_mun',$request->param('order_mun'))->update(['shenhe'=>1]);
        }
    }

    public function quxiao(Request $request){
        if ($request->isAjax()){

            if (OrderModel::where('order_mun',$request->param('order_mun'))->update(['status'=>6])){
                return msg(1,url('index'),'取消成功!');
            }else{
                return msg(-1,[],'取消失败!');
            }
        }
    }

    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton($id)
    {
        return [
            '详情' => [
                'auth' => 'order/orderinfo',
                'href' => url('order/orderinfo', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ],
            '推送' => [
                'auth' => 'order/tuisong',
                'href' => url('order/tuisong', ['id' => $id]),
                'btnStyle' => 'danger',
                'icon' => 'label label-primary set'
            ]
        ];
    }


    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButtons($id)
    {
        return [
            '详情' => [
                'auth' => 'order/orderinfos',
                'href' => url('order/orderinfos', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ],
//            '删除' => [
//                'auth' => 'order/orderdel',
//                'href' => "javascript:orderDel(" . $id . ")",
//                'btnStyle' => 'danger',
//                'icon' => 'fa fa-trash-o'
//            ]
        ];
    }
}
